<?php

namespace App\Http\Controllers\Admin\SystemSet\ParamsManager;

use App\Exceptions\BasicException;
use App\Http\Controllers\BaseController;
use Illuminate\Http\Request;    //引用http请求类
use App\Response\Response;

class ParamsGlobalSetController extends BaseController {

    /**
     * @api {put} /system-set/params-manager/global/set 参数设置-批量修改
     * @apiVersion 0.1.0
     * @apiName 系统设置-参数设置-批量修改
     * @apiGroup 系统设置
     *
     * @apiParam {map}    config                       配置内容 必传
     *
     * @apiSuccessExample 成功响应
     *
     *      {"code":200,"data":true}
     *
     * @apiError 10001 参数校验失败
     *
     * @apiErrorExample 错误响应
     *
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     *
     */
    public function edit(Request $request) {
        //参数校验
        try {
            $this->validate($request, [
                'config' => 'required|array',
            ]);
        } catch (\Exception $e) {
            throw new BasicException(10001, json_encode($e->errors()));
        }

        $params = $request->input();

        try {
            app('repo_config')->saveGlobalConfig($params['config']);
        } catch (\Exception $e) {
            throw new BasicException(10001, "更新失败！" . $e->getMessage());
        }

        return Response::sendData(true);
    }

    /**
     * @api {get} /system-set/params-manager/global/set 参数设置-获取数据
     * @apiVersion 0.1.0
     * @apiName 系统设置-参数设置-获取数据
     * @apiGroup 系统设置
     *
     * @apiParam {number} group_type 分组类型 可选
     *
     *
     * @apiSuccessExample 成功响应
     *
     *
    {
    "code": 200,
    "data": [
        {
            "id(序号)": 116,
            "key(配置标志)": "USER_RECHARGE_ZERO",
            "type(配置类型)": 4,
            "group(配置分组)": 1,
            "name(配置名称)": "充值只要1分钱的用户",
            "desc(配置项说明)": "充值只要1分钱的用户；只有测试环境生效",
            "status(是否启用 1：启用 0：禁用)": 0,
            "value(配置值)": "302928,652761,232706,617040,888888",
            "sort(排序)": 0
        }
    ]
     *
     *
     */
    public function getByGroup(Request $request) {
        //参数校验
        try {
            $this->validate($request, [
                'group_type' => 'required|numeric',
            ]);
        } catch (\Exception $e) {
            throw new BasicException(10001, json_encode($e->errors()));
        }

        $typeRes = app('repo_config')->queryConfig('CONFIG_GROUP_LIST');

        $typeMap = empty($typeRes) ? [] : $typeRes->parse();

        if (!empty($request->input("group_type")) && !isset($typeMap[$request->input("group_type")])) {
            throw new BasicException(10001, "配置类型不合法！");
        }

        $list = app('repo_config')->queryByGroup($request->input("group_type"));

        return Response::sendData($list);
    }

}
